<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>至本电商 - 客服聊天</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
</head>
<body>
    <div class="chat-container">
        <!-- 左侧菜单 -->
        <div class="sidebar">
            <div class="sidebar-header">
                <h2>至本客服</h2>
            </div>
            <div class="sidebar-menu">
                <div class="menu-item active" data-view="chat">
                    <i class="fas fa-comments"></i>
                    <span>聊天</span>
                </div>
                <div class="menu-item" data-view="transfer">
                    <i class="fas fa-user-tie"></i>
                    <span>转接人工</span>
                </div>
                <div class="menu-item" data-view="orders">
                    <i class="fas fa-shopping-cart"></i>
                    <span>我的订单</span>
                </div>
                <div class="menu-item" data-view="faq">
                    <i class="fas fa-question-circle"></i>
                    <span>常见问题</span>
                </div>
                <div class="menu-item" data-view="logout">
                    <i class="fas fa-sign-out-alt"></i>
                    <span>退出登录</span>
                </div>
            </div>
        </div>

        <!-- 聊天区域 -->
        <div class="chat-area">
            <!-- 聊天视图 -->
            <div class="view" id="chat-view">
                <div class="chat-header">
                    <h3>智能客服</h3>
                </div>
                <div class="chat-messages" id="chat-messages">
                    <!-- 消息会通过JavaScript动态加载 -->
                    <div class="message received">
                        <div class="message-content">
                            您好！欢迎咨询至本电商客服，我能为您提供产品信息、订单查询、售后等服务，请问有什么可以帮助您的？
                        </div>
                        <div class="message-time">客服机器人</div>
                    </div>
                </div>
                <div class="chat-input-area">
                    <form id="chat-form">
                        <textarea class="chat-input" id="message-input" placeholder="请输入您的问题..." required></textarea>
                        <button type="submit" class="send-btn">发送</button>
                    </form>
                </div>
            </div>

            <!-- 转接人工视图 -->
            <div class="view" id="transfer-view" style="display: none; padding: 20px; text-align: center;">
                <div class="waiting-indicator">
                    <i class="fas fa-circle-notch fa-spin fa-3x"></i>
                    <h3 style="margin-top: 20px;">正在等待人工客服接入...</h3>
                    <p style="margin-top: 10px; color: #7f8c8d;">请耐心等待，我们会尽快为您转接</p>
                </div>
            </div>

            <!-- 我的订单视图 -->
            <div class="view" id="orders-view" style="display: none;">
                <div class="orders-container">
                    <div class="orders-header">
                        <h2>我的订单</h2>
                    </div>
                    <div class="orders-list" id="orders-list">
                        <!-- 订单会通过JavaScript动态加载 -->
                        <div class="loading-orders">
                            <i class="fas fa-circle-notch fa-spin"></i>
                            <span>正在加载订单...</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 常见问题视图 -->
            <div class="view" id="faq-view" style="display: none; padding: 20px;">
                <h2 style="margin-bottom: 20px;">常见问题</h2>
                <div class="faq-list">
                    <div class="faq-item" style="margin-bottom: 15px;">
                        <h3 style="color: #3498db; cursor: pointer;">如何查询我的订单状态？</h3>
                        <p style="margin-top: 5px; display: none;">您可以在"我的订单"中查看所有订单状态，或直接向客服发送"查询订单状态"并提供订单号。</p>
                    </div>
                    <div class="faq-item" style="margin-bottom: 15px;">
                        <h3 style="color: #3498db; cursor: pointer;">如何修改收货地址？</h3>
                        <p style="margin-top: 5px; display: none;">对于已付款但未发货的订单，您可以在"我的订单"中找到相应订单，点击"修改地址"进行操作。</p>
                    </div>
                    <div class="faq-item" style="margin-bottom: 15px;">
                        <h3 style="color: #3498db; cursor: pointer;">如何申请退货/换货？</h3>
                        <p style="margin-top: 5px; display: none;">对于已收货的订单，您可以在"我的订单"中找到相应订单，点击"申请售后"按钮提交退货/换货申请。</p>
                    </div>
                    <div class="faq-item" style="margin-bottom: 15px;">
                        <h3 style="color: #3498db; cursor: pointer;">产品的保质期是多久？</h3>
                        <p style="margin-top: 5px; display: none;">我们的产品保质期通常为3年，具体请查看产品包装上的说明。</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 地址修改模态框 -->
    <div id="address-modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); justify-content: center; align-items: center;">
        <div style="background-color: white; padding: 20px; border-radius: 8px; width: 90%; max-width: 500px;">
            <h3 style="margin-bottom: 15px;">修改收货地址</h3>
            <form id="address-form">
                <input type="hidden" id="address-order-id">
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px;">新收货地址</label>
                    <textarea id="new-address" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; min-height: 100px;" required></textarea>
                </div>
                <div style="display: flex; justify-content: flex-end; gap: 10px;">
                    <button type="button" id="cancel-address" class="btn-secondary">取消</button>
                    <button type="submit" class="btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 售后申请模态框 -->
    <div id="after-sales-modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); justify-content: center; align-items: center;">
        <div style="background-color: white; padding: 20px; border-radius: 8px; width: 90%; max-width: 500px;">
            <h3 style="margin-bottom: 15px;">申请售后</h3>
            <form id="after-sales-form">
                <input type="hidden" id="after-sales-order-id">
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px;">退货/换货原因</label>
                    <textarea id="after-sales-reason" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; min-height: 100px;" required></textarea>
                </div>
                <div style="display: flex; justify-content: flex-end; gap: 10px;">
                    <button type="button" id="cancel-after-sales" class="btn-secondary">取消</button>
                    <button type="submit" class="btn-primary">提交申请</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            // 加载聊天历史
            loadChatHistory();

            // 加载订单
            loadUserOrders();

            // 添加 handleLogout 函数
            function handleLogout() {
                fetch('/logout')
                    .then(() => {
                        window.location.href = '/login';
                    })
                    .catch(error => {
                        console.error('退出登录错误:', error);
                        window.location.href = '/login';
                    });
            }

            // 菜单切换
            document.querySelectorAll('.menu-item').forEach(item => {
                item.addEventListener('click', function() {
                    const view = this.getAttribute('data-view'); // 获取 view 值
                    // 特殊处理
                    if (view === 'logout') {
                        if (confirm('确定要退出登录吗？')) {
                            handleLogout();
                        }
                        return; // 直接返回，不执行后续视图切换
                    }
                    // 移除所有活动状态
                    document.querySelectorAll('.menu-item').forEach(menu => {
                        menu.classList.remove('active');
                    });
                    this.classList.add('active');

                    // 隐藏所有视图
                    document.querySelectorAll('.view').forEach(view => {
                        view.style.display = 'none';
                    });

                    // 显示对应的视图
                    const viewId = this.getAttribute('data-view') + '-view';
                    document.getElementById(viewId).style.display = viewId === 'chat-view' ? 'flex' : 'block';

                    // 特殊视图处理
                    if (viewId === 'transfer-view') {
                        // 发送转接人工请求
                        requestHumanChat();
                    } else if (viewId === 'orders-view') {
                        // 如果需要，可以在这里加载订单
                        loadUserOrders();
        }

                });
            });

            // 聊天表单提交
            document.getElementById('chat-form').addEventListener('submit', async function(e) {
                e.preventDefault();

                const messageInput = document.getElementById('message-input');
                const message = messageInput.value.trim();

                if (message) {
                    // 添加用户消息到界面
                    addMessageToChat(message, 'sent');

                    // 清空输入框
                    messageInput.value = '';

                    // 发送消息到服务器
                    try {
                        const response = await fetch('/api/send_message', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({ message: message })
                        });

                        const data = await response.json();

                        if (data.success) {
                            // 添加机器人回复到界面
                            addMessageToChat(data.response, 'received');
                        } else {
                            addMessageToChat('抱歉，发送消息失败，请重试', 'received');
                        }
                    } catch (error) {
                        console.error('发送消息错误:', error);
                        addMessageToChat('抱歉，发送消息失败，请重试', 'received');
                    }
                }
            });

            // 常见问题折叠效果
            document.querySelectorAll('.faq-item h3').forEach(header => {
                header.addEventListener('click', function() {
                    const content = this.nextElementSibling;
                    content.style.display = content.style.display === 'none' ? 'block' : 'none';
                });
            });

            // 地址修改模态框
            document.getElementById('cancel-address').addEventListener('click', function() {
                document.getElementById('address-modal').style.display = 'none';
            });

            document.getElementById('address-form').addEventListener('submit', async function(e) {
                e.preventDefault();

                const orderId = document.getElementById('address-order-id').value;
                const newAddress = document.getElementById('new-address').value.trim();

                if (orderId && newAddress) {
                    try {
                        const response = await fetch('/api/update_address', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({
                                order_id: orderId,
                                new_address: newAddress
                            })
                        });

                        const data = await response.json();

                        if (data.success) {
                            alert('地址修改成功');
                            document.getElementById('address-modal').style.display = 'none';
                            loadUserOrders(); // 重新加载订单
                        } else {
                            alert(data.message);
                        }
                    } catch (error) {
                        console.error('修改地址错误:', error);
                        alert('修改地址失败，请重试');
                    }
                }
            });

            // 售后申请模态框
            document.getElementById('cancel-after-sales').addEventListener('click', function() {
                document.getElementById('after-sales-modal').style.display = 'none';
            });

            document.getElementById('after-sales-form').addEventListener('submit', async function(e) {
                e.preventDefault();

                const orderId = document.getElementById('after-sales-order-id').value;
                const reason = document.getElementById('after-sales-reason').value.trim();

                if (orderId && reason) {
                    try {
                        const response = await fetch('/api/apply_after_sales', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({
                                order_id: orderId,
                                reason: reason
                            })
                        });

                        const data = await response.json();

                        if (data.success) {
                            alert('售后申请已提交');
                            document.getElementById('after-sales-modal').style.display = 'none';
                            loadUserOrders(); // 重新加载订单
                        } else {
                            alert(data.message);
                        }
                    } catch (error) {
                        console.error('提交售后申请错误:', error);
                        alert('提交售后申请失败，请重试');
                    }
                }
            });
        });

        // 添加消息到聊天界面
        function addMessageToChat(message, type) {
            const chatMessages = document.getElementById('chat-messages');

            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${type}`;

            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content';
            contentDiv.textContent = message;

            const timeDiv = document.createElement('div');
            timeDiv.className = 'message-time';

            // 设置时间和发送者
            const now = new Date();
            const timeString = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;

            if (type === 'sent') {
                timeDiv.textContent = `我 ${timeString}`;
            } else {
                timeDiv.textContent = `客服机器人 ${timeString}`;
            }

            messageDiv.appendChild(contentDiv);
            messageDiv.appendChild(timeDiv);
            chatMessages.appendChild(messageDiv);

            // 滚动到底部
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        // 加载聊天历史
        async function loadChatHistory() {
            try {
                // 加载用户消息
                const userMessagesResponse = await fetch('/api/get_chat_history?sender_type=user');
                const userMessagesData = await userMessagesResponse.json();

                // 加载机器人消息
                const botMessagesResponse = await fetch('/api/get_chat_history?sender_type=bot');
                const botMessagesData = await botMessagesResponse.json();

                const chatMessages = document.getElementById('chat-messages');
                chatMessages.innerHTML = '';

                // 合并并排序所有消息
                const allMessages = [];

                if (userMessagesData.success) {
                    userMessagesData.history.forEach(item => {
                        allMessages.push({
                            ...item,
                            sortKey: new Date(item.created_at).getTime()
                        });
                    });
                }

                if (botMessagesData.success) {
                    botMessagesData.history.forEach(item => {
                        allMessages.push({
                            ...item,
                            sortKey: new Date(item.created_at).getTime()
                        });
                    });
                }

                // 按时间排序
                allMessages.sort((a, b) => a.sortKey - b.sortKey);

                // 显示所有消息
                allMessages.forEach(item => {
                    if (item.sender_type === 'user') {
                        // 用户消息
                        addMessageToChat(item.message, 'sent', item.created_at);
                    } else if (item.sender_type === 'bot') {
                        // 机器人消息
                        addMessageToChat(item.message, 'received', item.created_at, 'bot');
                    }
                });
            } catch (error) {
                console.error('加载聊天历史错误:', error);
            }
        }

        // 添加消息到聊天界面
        function addMessageToChat(message, type, timestamp, sender = null) {
            const chatMessages = document.getElementById('chat-messages');

            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${type}`;

            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content';
            contentDiv.textContent = message;

            const timeDiv = document.createElement('div');
            timeDiv.className = 'message-time';

            // 设置时间和发送者
            const date = timestamp ? new Date(timestamp) : new Date();
            const timeString = `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;

            if (type === 'sent') {
                timeDiv.textContent = `我 ${timeString}`;
            } else {
                if (sender === 'bot') {
                    timeDiv.textContent = `客服机器人 ${timeString}`;
                } else if (sender === 'admin') {
                    timeDiv.textContent = `客服（人工） ${timeString}`;
                }
            }

            messageDiv.appendChild(contentDiv);
            messageDiv.appendChild(timeDiv);
            chatMessages.appendChild(messageDiv);

            // 滚动到底部
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }
        // 加载用户订单
        async function loadUserOrders() {
            try {
                const response = await fetch('/api/get_user_orders');
                const data = await response.json();

                const ordersList = document.getElementById('orders-list');

                if (data.success) {
                    if (data.orders.length > 0) {
                        ordersList.innerHTML = '';

                        data.orders.forEach(order => {
                            const orderCard = document.createElement('div');
                            orderCard.className = 'order-card';

                            // 订单状态样式
                            let statusClass = '';
                            switch(order.status) {
                                case '已付款':
                                    statusClass = 'status-paid';
                                    break;
                                case '已发货':
                                    statusClass = 'status-shipped';
                                    break;
                                case '已收货':
                                    statusClass = 'status-received';
                                    break;
                                case '售后中':
                                case '售后完成':
                                    statusClass = 'status-after-sales';
                                    break;
                            }
                            // 在订单处理部分添加申请售后功能
                            function initOrderActions() {
                                document.querySelectorAll('.request-after-sales').forEach(btn => {
                                    btn.addEventListener('click', function() {
                                        const orderId = this.getAttribute('data-order-id');
                                        document.getElementById('after-sales-order-id').value = orderId;
                                        document.getElementById('after-sales-modal').style.display = 'flex';
                                    });
                                });

                                // 提交售后申请
                                document.getElementById('after-sales-form').addEventListener('submit', async function(e) {
                                    e.preventDefault();
                                    const orderId = document.getElementById('after-sales-order-id').value;
                                    const reason = document.getElementById('after-sales-reason').value;

                                    try {
                                        const response = await fetch('/api/request-after-sales', {
                                            method: 'POST',
                                            headers: {
                                                'Content-Type': 'application/json'
                                            },
                                            body: JSON.stringify({
                                                order_id: orderId,
                                                reason: reason
                                            })
                                        });

                                        const data = await response.json();
                                        if (data.success) {
                                            alert('售后申请已提交，请等待处理');
                                            document.getElementById('after-sales-modal').style.display = 'none';
                                            loadUserOrders(); // 刷新订单列表
                                        } else {
                                            alert('提交失败: ' + data.message);
                                        }
                                    } catch (error) {
                                        console.error('提交售后申请失败:', error);
                                        alert('提交失败，请重试');
                                    }
                                });
                            }

                            // 构建订单HTML
                            orderCard.innerHTML = `
                                <div class="order-header">
                                    <div class="order-id">订单号: ${order.order_id}</div>
                                    <div class="order-status ${statusClass}">${order.status}</div>
                                </div>
                                <div class="order-details">
                                    <div class="order-row"><strong>产品:</strong> ${order.product_name}</div>
                                    <div class="order-row"><strong>数量:</strong> ${order.quantity}</div>
                                    <div class="order-row"><strong>总金额:</strong> ¥${order.total_amount}</div>
                                    <div class="order-row"><strong>收货地址:</strong> ${order.shipping_address}</div>
                                    <div class="order-row">
                                        <strong>时间:</strong>
                                        ${order.payment_time ? `付款: ${formatDate(order.payment_time)}` : ''}
                                        ${order.shipping_time ? ` | 发货: ${formatDate(order.shipping_time)}` : (order.status === '已付款' ? ' | 发货: 未发货' : '')}
                                        ${order.receive_time ? ` | 收货: ${formatDate(order.receive_time)}` : (order.status === '已发货' ? ' | 收货: 未收货' : '')}
                                    </div>
                                </div>
                                <div class="order-actions">
                                    ${order.status === '已付款' ? `<button class="btn-secondary edit-address" data-order-id="${order.order_id}">修改地址</button>` : ''}
                                    ${(order.status === '已收货' || order.status === '已发货') && order.status !== '售后中' && order.status !== '售后完成' ?
                                        `<button class="btn-danger apply-after-sales" data-order-id="${order.order_id}">申请售后</button>` : ''}
                                </div>
                            `;

                            ordersList.appendChild(orderCard);
                        });

                        // 绑定修改地址按钮事件
                        document.querySelectorAll('.edit-address').forEach(button => {
                            button.addEventListener('click', function() {
                                const orderId = this.getAttribute('data-order-id');
                                document.getElementById('address-order-id').value = orderId;
                                document.getElementById('address-modal').style.display = 'flex';
                            });
                        });

                        // 绑定申请售后按钮事件
                        document.querySelectorAll('.apply-after-sales').forEach(button => {
                            button.addEventListener('click', function() {
                                const orderId = this.getAttribute('data-order-id');
                                document.getElementById('after-sales-order-id').value = orderId;
                                document.getElementById('after-sales-modal').style.display = 'flex';
                            });
                        });
                    } else {
                        ordersList.innerHTML = '<p style="text-align: center; padding: 20px;">暂无订单记录</p>';
                    }
                } else {
                    ordersList.innerHTML = '<p style="text-align: center; padding: 20px; color: #e74c3c;">加载订单失败</p>';
                }
            } catch (error) {
                console.error('加载订单错误:', error);
                document.getElementById('orders-list').innerHTML = '<p style="text-align: center; padding: 20px; color: #e74c3c;">加载订单失败</p>';
            }
        }

        // 格式化日期
        function formatDate(dateString) {
            const date = new Date(dateString);
            return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
        }

        // 请求转接人工客服
        async function requestHumanChat() {
            try {
                const response = await fetch('/api/send_message', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ message: '转人工客服' })
                });

                const data = await response.json();

                if (data.success) {
                    // 显示机器人回复
                    const waitingDiv = document.querySelector('#transfer-view .waiting-indicator');
                    waitingDiv.innerHTML = `
                        <i class="fas fa-circle-notch fa-spin fa-3x"></i>
                        <h3 style="margin-top: 20px;">${data.response}</h3>
                        <p style="margin-top: 10px; color: #7f8c8d;">请耐心等待，我们会尽快为您转接</p>
                    `;

                    // 定时检查是否已接入人工客服
                    checkHumanChatStatus();
                }
            } catch (error) {
                console.error('请求转接人工错误:', error);
            }
        }

        // 检查是否已接入人工客服
        function checkHumanChatStatus() {
            // 这里应该定期检查服务器，看是否已接入人工客服
            // 简化处理，实际项目中应该实现轮询或WebSocket
            setTimeout(() => {
                // 模拟还未接入
                checkHumanChatStatus();
            }, 5000);
        }
    </script>
</body>
</html>
